package com.lanju.app.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class AppUtil {
	private static Log log = LogFactory.getLog(AppUtil.class);
	
	private static SimpleDateFormat sdfyyyyMMddHHmm = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm");
	private static SimpleDateFormat sdfyyyyMMddHHmmss = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private static SimpleDateFormat sdfyyyyMMdd = new SimpleDateFormat(
			"yyyy-MM-dd");

	public String formatDate_yyyyMMddHHmm(Date date) {
		if (null == date)
			return "";
		return sdfyyyyMMddHHmm.format(date);
	}

	public String formatDate_yyyyMMdd(Date date) {
		if (null == date)
			return "";
		return sdfyyyyMMdd.format(date);
	}

	public String formatDate_yyyyMMddHHmmss(Date date) {
		if (null == date)
			return "";
		return sdfyyyyMMddHHmmss.format(date);
	}

	public static String oss_bucket_thumb150x150 = "?x-oss-process=image/resize,h_150,w_150";
	public static String oss_psth = "https://lanju.oss-cn-shenzhen.aliyuncs.com/";

	private static GsonBuilder gb = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls();// .registerTypeAdapter(String.class,
																		// new
																		// StringAdapter()).serializeNulls();
	public static Gson createGson() {
		return gb.create();
	}

	/**
	 * 生成随即密码
	 * 
	 * @param pwd_len
	 *            生成的密码的总长度
	 * @return 密码的字符串
	 */
	public String genRandomNum(int pwd_len) {
		final int maxNum = 36;
		int i; // 生成的随机数
		int count = 0; // 生成的密码的长度
		char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
				'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
				'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		StringBuffer pwd = new StringBuffer("");
		Random r = new Random();
		while (count < pwd_len) {
			// 生成随机数，取绝对值，防止 生成负数，

			i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1

			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count++;
			}
		}
		return pwd.toString();
	}

	@SuppressWarnings({"rawtypes" })
	public <T> T SendToUrlByBean(String url, Object brb, Class clazz) {
		return SendToUrlByBean(url,brb,clazz,5000);
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public <T> T SendToUrlByBean(String url, Object brb, Class clazz, int timeout ) {
		Gson gson = createGson();
		String json = gson.toJson(brb);
		log.debug(">>>"+json);
		String result = connectURL(url, json, timeout);
		log.debug("<<<"+result);
		T res = (T) gson.fromJson(result, clazz);
		return res;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public <T> T SendToUrlByParam(String url, Map<String,String> map, Class clazz) {
		Gson gson = createGson();
		StringBuffer params = new StringBuffer();
		int i = 0;
		if(map!=null){
			for(String key:map.keySet()){
				if(i==0)
					params.append(key).append("=").append(map.get(key));
				else
					params.append("&").append(key).append("=").append(map.get(key));
				i++;
			}
		}
		String send = params.toString();
		log.debug(">>>"+i+" parms:"+send);
		String result = connectURL(url, send, 5000);
		log.debug("<<<"+result);
		T res = (T) gson.fromJson(result, clazz);
		return res;
	}
	
	public String connectURL(String dest_url, String content, int timeout) {
		
		String rec_string = "";
		URL url = null;
		HttpURLConnection urlconn = null;
		OutputStream out = null;
		BufferedReader rd = null;
		try {
			url = new URL(dest_url);
			urlconn = (HttpURLConnection) url.openConnection();
			if(timeout>1000)
				urlconn.setReadTimeout(timeout);
			else
				urlconn.setReadTimeout(5000);
			// urlconn.setRequestProperty("content-type", "text/html;charset=UTF-8");
			urlconn.setRequestMethod("POST");
			
			urlconn.setDoInput(true);
			urlconn.setDoOutput(true);
			out = urlconn.getOutputStream();
			out.write(content.getBytes("UTF-8"));
			out.flush();
			out.close();
			rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream(),"UTF-8"));
			StringBuffer sb = new StringBuffer();
			int ch;
			while ((ch = rd.read()) > -1)
				sb.append((char) ch);
			rec_string = sb.toString();

		} catch (Exception e) {
			if(content.contains("C012")){
				log.warn("调用C012接口异常" + e.getMessage());
			}else{
				log.error("apputil connectURL 异常", e);
			}
		} finally {
			try {
				if (rd != null) {
					rd.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if (urlconn != null) {
					urlconn.disconnect();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return rec_string;
	}
	
	public static String getFixLenthString(int strLength) {  	      
	    Random rm = new Random();  	      
	    // 获得随机数  
	    double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);  	  
	    // 将获得的获得随机数转化为字符串  
	    String fixLenthString = String.valueOf(pross);  	  
	    // 返回固定的长度的随机数  
	    return fixLenthString.substring(2, strLength + 2);  
	}  
	
	public static String getNoContainNull(String str){
		if(str==null){
			str="";
		}
		return str;
	}
	
	public static void main(String[] args){
		System.out.println(getFixLenthString(10));
	}
}
